# @Time    :2025/4/8 9:58
"""
 线程安全问题
"""
import threading
import time

# 实现卖票功能的函数
def func():
    global ticket_num
    while True:
        # 获取锁
        lock.acquire()
        if ticket_num <= 0:
            # 释放锁
            lock.release()
            break
        time.sleep(0.3)
        ticket_num -= 1
        lock.release()
        print(f"当前线程{threading.current_thread().name}卖了1张，还剩:{ticket_num}张")


if __name__ == "__main__":
    # 定义一个全局变量
    ticket_num = 100
    lock = threading.Lock()

    threads = [threading.Thread(target=func, name="窗口" + str(i)) for i in range(3)]#range(3)：三个线程
    [t.start() for t in threads]
    [t.join() for t in threads]
    # 上面的列表推导式 等价于下边这种写法
    # for t in threads:
    #     t.start()
    print(f"当前线程{threading.current_thread().name}", ticket_num)
